<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <link rel="stylesheet" th:href="@{/css/layui.css}" href="/css/layui.css" />
  <th:block th:include="include :: header('首页')" />
  <th:block th:include="include :: layout-latest-css" />
  <th:block th:include="include :: ztree-css" />
  <link rel="stylesheet" th:href="@{/css/main.css}" href="/css/main.css" />
  <style>
    .fixed-table-body {
      height: 400px;
      overflow: auto;
      border: 1px solid #ccc;
    }

    .table-striped table>thead>tr>th,
    .table-striped table>tbody>tr>th,
    .table-striped table>tfoot>tr>th,
    .table-striped table>thead>tr>td,
    .table-striped table>tbody>tr>td,
    .table-striped table>tfoot>tr>td { 
      border: 1px solid #e7eaec;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="leftCard">
      <div class="topCard search-collapse">
        <div class="col-sm-10">
          <h5>通知公告 </h5>
        </div>
        <div class="ibox-content" style="height:150px;">
          <ul th:each="item,userStat: ${list_notic}">
            <li th:if="${userStat.index} lt 6"><a th:onclick="javascript:opn_db([[${item.Url_ck}]],'通知公告')"><span
                  th:text="${#dates.format(item.createTime, 'yyyy-MM-dd')}"></span>&emsp;&emsp;<span
                  th:text="${item.noticeTitle}"></span></a></li>
          </ul>
        </div>
      </div>

      <div class="buttonCard">
        <div class="leftChart search-collapse">
          <div class="title">
            <p>数据统计饼状图</p>
          </div>
          <h3 class="titleErr" style="text-align: center; line-height: 310px; display: none">
            暂无数据
          </h3>
          <div class="echarsbox">
            <div id="cake" style="width: 100%; height: 310px"></div>
          </div>
        </div>
        <div class="rightChart search-collapse">
          <div class="title">
            <p>数据异常柱状图</p>
          </div>
          <h3 class="titleErr" style="text-align: center; line-height: 310px; display: none">
            暂无数据
          </h3>
          <div class="echarsbox">
            <div id="main" style="width: 100%; height: 310px"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="rightCard search-collapse table-striped">
      <table id="bootstrap-table1"></table>
    </div>
  </div>
  <script src="/js/echarts.min.js" th:href="@{/js/echart.min.js}"></script>
  <script src="/js/echarts.js" th:src="@{/js/echarts.js}"></script>
  <th:block th:include="include :: footer" />
  <th:block th:include="include :: layout-latest-js" />
  <th:block th:include="include :: ztree-js" />
</body>

<script src="/js/layui.js" th:href="@{/js/layui.js}"></script>
<script>
  $(function () {
    renderChart();
    queryUserList();
  });
  function opn_db(str_url, type_name) {

    $.modal.openTab(type_name, str_url);

  }
  // 表格
  function queryUserList() {
    var options = {
      id: "bootstrap-table1",
      url: "/youtian/scene-category/scencePointlist/?sceneId=19&pageSize=10000",
      method: "get",
      showSearch: false,
      pagination: false,
      sortable: false, // 不使用排序
      modalName: "用户",
      onClickRow: onClickRow,
      onLoadSuccess: function (data) {
        mergeCells(data, "sceneName", 1, $("#bootstrap-table1")); //行合并
      },
      rowStyle: function (row, index) {
        var classes = ["bg-blue", "bg-green", "bg-red"];
        console.log(row, index, "index");
        if (row.dataState != "异常") {
          return {
            classes: classes[index / 2],
          };
        }
        return {
          css: {
            color: "red",
          },
        };
      },
      columns: [
        {
          field: "sceneName",
          title: "场景名称",
          align: "center",
        },
        {
          field: "pointName",
          title: "采集数据点位",
          align: "center",
        },
        {
          field: "upperLimit",
          title: "上限值",
          align: "center",
        },
        {
          field: "lowerLimit",
          title: "下限值",
          align: "center",
        },
        {
          field: "dataState",
          title: "数据状态",
          align: "center",
        },
        {
          field: "value",
          title: "采集值",
          align: "center",
        },
      ],
    };
    $.table.init(options);
  }
  // 场景检测图表
  function renderChart(id) {
    $.ajax({
      url: "/youtian/scene-category/getSceneCategoryAll",
      type: "get",
      success: function (res) {
        console.log(res, '--------------------');
        if (res.data.length <= 0) {
          $(".titleErr").css("display", "block");
          $(".echarsbox").css("display", "none");
          return;
        }
        let echartData = res.data;
        // 柱状图
        var chartDom = document.getElementById("main");
        var myChart = echarts.init(chartDom);
        var option;
        let echartY = [];
        let errorTagCount = [];
        let tagCount = [];
        echartData.forEach((item) => {
          echartY.push(item.sceneName);
          errorTagCount.push(item.errorTagCount);
          tagCount.push(item.tagCount);
        });
        console.log(echartData, echartY, errorTagCount, tagCount);
        option = {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          legend: {},
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "value",
            name: "数量",
          },
          yAxis: {
            type: "category",
            name: "场景名称",
            data: echartY,
          },
          series: [
            {
              name: "异常数量",
              type: "bar",
              stack: "total",
              label: {
                show: true,
              },
              emphasis: {
                focus: "series",
              },
              data: errorTagCount,
            },

            {
              name: "监测点数量",
              type: "bar",
              stack: "total",
              label: {
                show: true,
              },
              emphasis: {
                focus: "series",
              },
              data: tagCount,
            },
          ],
        };

        option && myChart.setOption(option);

        // 饼状图
        var chartDom = document.getElementById("cake");
        var myChart = echarts.init(chartDom);
        var option;
        option = {
          title: {
            text: "数据统计饼状图",
            left: "center",
          },
          tooltip: {
            trigger: "item",
          },
          legend: {
            orient: "vertical",
            left: "left",
          },
          series: [
            {
              name: "场景名称",
              type: "pie",
              radius: "50%",
              data: pieChartData(res.data),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
            },
          ],
        };
        $(".isShow").css({
          display: "none",
        });
        option && myChart.setOption(option);
      },
    });
  }
  // 点击表格显示图表
  // 定时器
  var setTimeData = "";
  var list = null;
  $('#bootstrap-table1').mouseleave(function () {
    clearInterval(setTimeData)
    $("#noneBox").remove()
  })
  function onClickRow(row, el) {
    clearInterval(setTimeData);
    let echartDom = el.children("#noneBox");
    console.log(echartDom[0], "echartDom");
    if (echartDom[0]) {
      return echartDom.remove();
    }
    console.log(row, "row");
    let sourceTag = row.pointId;
    list = {
      sourceTag: sourceTag,
      params: {
        beginTime: "",
        endTime: "",
      },
    };
    console.log(list, "list");
    $.ajax({
      url: `/youtian/scene-category/selectSourceTagHistoryListBySourceTag`,
      type: "post",
      dataType: "json",
      data: JSON.stringify(list),
      headers: { "Content-Type": "application/json" },
      success: function (res) {
        console.log(res, "res");
        el.mouseleave(function () {
          console.log(el.children("td"), el.children("td").eq(3), "123");
          $(".tip_text").remove();
        });
        if (res.data.length <= 0) {
          $(".tip_text").remove();
          return el.append(`<div class="tip_text">暂无数据</div>`);
        }
        $("#noneBox").remove();
        el.append(`<div id="noneBox"></div>`);
        let upLimit = el.children("td").eq(2).text();
        let lowLimit = el.children("td").eq(3).text();
        console.log(parseInt(upLimit), parseInt(lowLimit), 'lowLimit');
        echart(parseInt(upLimit), parseInt(lowLimit), res.data);
      },
    });
  }
  // 饼状图
  // var chartDom = document.getElementById("cake");
  // var myChart = echarts.init(chartDom);
  // var option;
  // option = {
  //   title: {
  //     text: "数据统计饼状图",
  //     left: "center",
  //   },
  //   tooltip: {
  //     trigger: "item",
  //   },
  //   legend: {
  //     orient: "vertical",
  //     left: "left",
  //   },
  //   series: [
  //     {
  //       name: "场景名称",
  //       type: "pie",
  //       radius: "50%",
  //       data: pieChartData(res.data),
  //       emphasis: {
  //         itemStyle: {
  //           shadowBlur: 10,
  //           shadowOffsetX: 0,
  //           shadowColor: "rgba(0, 0, 0, 0.5)",
  //         },
  //       },
  //     },
  //   ],
  // };
  // $(".isShow").css({
  //   display: "none",
  // });
  // option && myChart.setOption(option);
  //     },
  //   });
  // }
  // 点击表格显示图表
  // 定时器
  var setTimeData = "";
  // let list = {};
  $('#bootstrap-table1').mouseleave(function () {
    clearInterval(setTimeData)
    $("#noneBox").remove()
  })
  function onClickRow(row, el) {
    clearInterval(setTimeData);
    let echartDom = el.children("#noneBox");
    console.log(echartDom[0], "echartDom");
    if (echartDom[0]) {
      return echartDom.remove();
    }
    console.log(row, "row");
    let sourceTag = row.pointId;
    list = {
      sourceTag: sourceTag,
      params: {
        beginTime: "",
        endTime: "",
      }
    };
    console.log(list, "list");
    $.ajax({
      url: `/youtian/scene-category/selectSourceTagHistoryListBySourceTag`,
      type: "post",
      dataType: "json",
      data: JSON.stringify(list),
      headers: { "Content-Type": "application/json" },
      success: function (res) {
        console.log(res, "res");
        el.mouseleave(function () {
          console.log(el.children("td"), el.children("td").eq(3), "123");
          $(".tip_text").remove();
        });
        if (res.data.length <= 0) {
          $(".tip_text").remove();
          return el.append(`<div class="tip_text">暂无数据</div>`);
        }
        $("#noneBox").remove();
        el.append(`<div id="noneBox"></div>`);
        let upLimit = el.children("td").eq(2).text();
        let lowLimit = el.children("td").eq(3).text();
        console.log(parseInt(upLimit), parseInt(lowLimit), 'lowLimit');
        echart(parseInt(upLimit), parseInt(lowLimit), res.data);
      },
    });
  }

  // 封装图表方法
  function echart(upLimit, lowlimit, options) {
    // let optionsSlice = options.slice(10, 20)
    // console.log(optionsSlice, 'optionsSlice');
    // // 图表数据
    // let dataLists = {
    //   data: [],
    //   cjTime: []
    // }
    // optionsSlice.forEach(item => {
    //   dataLists.data.push(item.value)
    //   dataLists.cjTime.push(item.cjTime)
    // })

    // // 页面最大值
    // let dataList = []
    // optionsSlice.forEach(item => {
    //   dataList.push(item.value)
    // });
    // dataList.sort((a, b) => {
    //   return b -a
    // })
    // console.log(dataList, 'dataList');
    var chartDom = document.getElementById("noneBox");
    var myChart = echarts.init(chartDom);
    var option;
    option = {
      tooltip: {
        trigger: "axis",
        boundaryGap: false,
      },
      xAxis: {
        name: "时间",
        type: "category",
        boundaryGap: false,
        data: ["1-1", "1-2", "1-3", "1-4", "1-5"],
      },
      yAxis: {
        name: "数量",
        type: "value",
        min: 0,
        max: 200,
        splitLine: {
          show: false,
        },
      },
      grid: {
        left: "15%",
        right: "20%",
        bottom: "10%",
        top: "20%",
      },
      visualMap: [
        {
          type: "piecewise",
          show: false,
          dimension: 1,
          seriesIndex: 0,
          hoverLink: true,
          pieces: [
            {
              // 不指定 min，表示 min 为无限大（-Infinity）。
              max: lowlimit, // 没有设置最小值，表明当前范围 [-Infinity, max] 变色
              color: "red",
            },
            {
              // 不指定 max，表示 max 为无限大（Infinity）。
              min: upLimit, // 没有设置最大值，表明当前范围 [min, Infinity] 变色
              color: "red",
            },
          ],
          outOfRange: {
            // 在选中范围外 的视觉元素，这里设置在正常范围内的图形颜色
            color: "blue",
          },
        },
      ],
      series: [
        {
          type: "line",
          smooth: true,
          symbol: "none",
          markLine: {
            symbol: "none",
            label: {
              show: true,
            },
            data: [
              {
                yAxis: lowlimit,
              },
              {
                yAxis: upLimit,
              },
            ],
          },
          // areaStyle: {},
          data: [10, 15, 140, 40, 150],
        },
      ],
    };
    option && myChart.setOption(option);
    setTimeData = setInterval(() => {
      $.ajax({
        url: `/youtian/scene-category/selectSourceTagHistoryListBySourceTag`,
        type: "post",
        dataType: "json",
        data: JSON.stringify(list),
        headers: { "Content-Type": "application/json" },
        success: function (res) {
          console.log(res, "length2");
          if (res.data && res.data.length) {
            option.series[0].data = [3, 45, 3, 45, 33];
            option && myChart.setOption(option);
          }
        },
      });
    }, 5000);
  }

  /**
   * 合并行
   * @param data  原始数据（在服务端完成排序）
   * @param fieldName 合并属性名称
   * @param colspan 列数
   * @param target 目标表格对象
   */
  function mergeCells(data, fieldName, colspan, target) {
    data = data.rows;
    console.log(data[0], "data");
    if (data.length == 0) {
      return;
    }
    var numArr = [];
    var value = data[0][fieldName];
    console.log(value, "value");
    var num = 0;
    for (var i = 0; i < data.length; i++) {
      if (value != data[i][fieldName]) {
        numArr.push(num);
        value = data[i][fieldName];
        num = 1;
        continue;
      }
      num++;
    }
    if (typeof value != "undefined" && value != "") {
      numArr.push(num);
    }
    var merIndex = 0;
    for (var i = 0; i < numArr.length; i++) {
      $(target).bootstrapTable("mergeCells", {
        index: merIndex,
        field: fieldName,
        colspan: colspan,
        rowspan: numArr[i],
      });
      merIndex += numArr[i];
    }
  }

  // 计算比例
  function pieChartData(arr) {
    console.log(arr);
    let total = arr.reduce((prev, next) => {
      return next.errorTagCount + prev;
    }, 0);
    var newArr = [];
    arr.forEach((item) => {
      var obj = {};
      obj.value = (item.errorTagCount / total).toFixed(2) * 100;
      obj.name = item.sceneName;
      newArr.push(obj);
    });
    return newArr;
  }
</script>

</html>